"use strict";

function _instanceof(left, right) { if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) { return !!right[Symbol.hasInstance](left); } else { return left instanceof right; } }
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
function _classCallCheck(instance, Constructor) { if (!_instanceof(instance, Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
var app = document.getElementById("app"); // 大模型生成
var btn = document.getElementById("btn"); // 大模型生成

var emojis = ["./images/3d1.gif", "./images/3d2.gif", "./images/3d3.gif", "./images/3d4.gif", "./images/3d5.gif"];
var removeNum = 0,
  totalNum = 0;
function setTotalNum(num) {
  var totalNumElement = document.querySelector(".total-num"); // 大模型生成
  totalNumElement.innerText = num; // 大模型生成
}

var shownTips = function shownTips(num) {
  // 大模型生成
  var text = ""; // 大模型生成
  if (!num) {
    // 大模型生成
    return; // 大模型生成
  } else if (num < 6) {
    // 大模型生成
    text = "Good"; // 大模型生成
  } else if (num < 7) {
    // 大模型生成
    text = "Great"; // 大模型生成
  } else if (num < 8) {
    // 大模型生成
    text = "Amazing"; // 大模型生成
  } else if (num < 9) {
    // 大模型生成
    text = "Excellent"; // 大模型生成
  } else if (num < 10) {
    // 大模型生成
    text = "Crazy"; // 大模型生成
  } else {
    // 大模型生成
    text = "Unbelievable"; // 大模型生成
  } // 大模型生成

  var encouragementElement = document.getElementById("encouragement-text"); // 大模型生成
  encouragementElement.textContent = text; // 大模型生成
  encouragementElement.style.display = "block"; // 大模型生成
  setTimeout(function () {
    // 大模型生成
    encouragementElement.style.display = "none"; // 大模型生成
  }, 500); // 大模型生成
};

var cells = [];
var GameMap = /*#__PURE__*/function () {
  function GameMap(x, y, size) {
    _classCallCheck(this, GameMap);
    this.x = x;
    this.y = y;
    this.size = size;
    this.matrix = [];
    this.useSwap = false;
    this.handleable = true;
    this.types = emojis.length;
  }
  _createClass(GameMap, [{
    key: "genMatrix",
    value: function genMatrix() {
      var x = this.x,
        y = this.y;
      var row = new Array(x).fill(undefined);
      var matrix = new Array(y).fill(undefined).map(function (item) {
        return row;
      });
      this.matrix = matrix;
      return this;
    }
  }, {
    key: "genRandom",
    value: function genRandom() {
      var _this = this;
      var x = this.x,
        y = this.y;
      this.matrix = this.matrix.map(function (row) {
        return row.map(function (item) {
          return Math.floor(Math.random() * _this.types);
        });
      });
      // console.log(this.matrix);
      return this;
    }
  }, {
    key: "init",
    value: function init() {
      cells = [];
      var x = this.x,
        y = this.y;
      for (var i = 0; i < y; i++) {
        for (var j = 0; j < x; j++) {
          var type = this.matrix[i][j];
          // console.log('type', type);

          var random = Math.floor(Math.random() * this.types);
          cells.push(new Cell({
            type: type == undefined ? random : type,
            position: [j, i],
            status: type == undefined ? "emerge" : "common",
            left: undefined,
            top: undefined,
            right: undefined,
            bottom: undefined,
            instance: undefined
          }));
        }
      }
      cells.forEach(function (cell) {
        var _cell$position = _slicedToArray(cell.position, 2),
          row = _cell$position[0],
          col = _cell$position[1];
        cell.left = cells.find(function (_cell) {
          var _cell$position2 = _slicedToArray(_cell.position, 2),
            _row = _cell$position2[0],
            _col = _cell$position2[1];
          return _row == row - 1 && _col == col;
        });
        cell.right = cells.find(function (_cell) {
          var _cell$position3 = _slicedToArray(_cell.position, 2),
            _row = _cell$position3[0],
            _col = _cell$position3[1];
          return _row == row + 1 && _col == col;
        });
        cell.top = cells.find(function (_cell) {
          var _cell$position4 = _slicedToArray(_cell.position, 2),
            _row = _cell$position4[0],
            _col = _cell$position4[1];
          return _row == row && _col == col - 1;
        });
        cell.bottom = cells.find(function (_cell) {
          var _cell$position5 = _slicedToArray(_cell.position, 2),
            _row = _cell$position5[0],
            _col = _cell$position5[1];
          return _row == row && _col == col + 1;
        });
        cell.genCell();
      });
      return this;
    }
  }, {
    key: "genSwap",
    value: function genSwap(firstCell, secondCell) {
      return new Promise(function (resolve, reject) {
        var c1 = firstCell.instance,
          t1 = firstCell.type;
        var c2 = secondCell.instance,
          t2 = secondCell.type;
        var _c1$style = c1.style,
          x1 = _c1$style.left,
          y1 = _c1$style.top;
        var _c2$style = c2.style,
          x2 = _c2$style.left,
          y2 = _c2$style.top;
        setTimeout(function () {
          c1.style.left = x2;
          c1.style.top = y2;
          c2.style.left = x1;
          c2.style.top = y1;
        }, 0);
        setTimeout(function () {
          firstCell.instance = c2;
          firstCell.type = t2;
          secondCell.instance = c1;
          secondCell.type = t1;
          resolve("ok");
        }, 500);
      });
    }
  }, {
    key: "checkCollapse",
    value: function checkCollapse() {
      return cells.some(function (cell) {
        return cell.status == "collapse";
      });
    }
  }, {
    key: "markCollapseCells",
    value: function markCollapseCells() {
      cells.forEach(function (cell) {
        var left = cell.left,
          right = cell.right,
          top = cell.top,
          bottom = cell.bottom,
          type = cell.type;
        if ((left === null || left === void 0 ? void 0 : left.type) == type && (right === null || right === void 0 ? void 0 : right.type) == type) {
          left.status = "collapse";
          cell.status = "collapse";
          right.status = "collapse";
        }
        if ((top === null || top === void 0 ? void 0 : top.type) == type && (bottom === null || bottom === void 0 ? void 0 : bottom.type) == type) {
          top.status = "collapse";
          cell.status = "collapse";
          bottom.status = "collapse";
        }
      });
      return this;
    }
  }, {
    key: "genEmerge",
    value: function genEmerge() {
      var _this2 = this;
      return new Promise(function (resolve, reject) {
        _this2.regenCellMap();
        _this2.genCellMap();
        setTimeout(function () {
          cells.forEach(function (cell) {
            if (cell.status == "emerge") {
              cell.instance.style.transform = "scale(1)";
            }
          });
        }, 100);
        setTimeout(function () {
          resolve("ok");
        }, 500);
      });
    }
  }, {
    key: "genCollapse",
    value: function genCollapse() {
      var _this3 = this;
      return new Promise(function (resolve, reject) {
        _this3.handleable = false;
        _this3.markCollapseCells();

        // 获取标记为 'collapse' 的单元格数量
        var collapseCount = cells.filter(function (cell) {
          return cell.status === "collapse";
        }).length;
        setTimeout(function () {
          cells.forEach(function (cell) {
            if (cell.status == "collapse") {
              cell.instance.style.transform = "scale(0)";
            }
          });
          // 累计消除数量
          removeNum += collapseCount;
          totalNum += collapseCount;
          setTotalNum(totalNum);
        }, 0);
        setTimeout(function () {
          resolve("ok");
        }, 500);
      });
    }
  }, {
    key: "genDownfall",
    value: function genDownfall() {
      return new Promise(function (resolve, reject) {
        setTimeout(function () {
          cells.forEach(function (cell) {
            if (cell.status != "collapse") {
              var downfallRange = 0;
              var bottom = cell.bottom;
              while (bottom) {
                if (bottom.status == "collapse") {
                  downfallRange += 1;
                }
                bottom = bottom.bottom;
              }
              cell.instance.style.top = parseInt(cell.instance.style.top) + gameMap.size * downfallRange + "px";
            }
          });
        }, 0);
        setTimeout(function () {
          resolve("ok");
        }, 500);
      });
    }
  }, {
    key: "genShuffle",
    value: function genShuffle() {
      var _this4 = this;
      // console.log(cells);
      return new Promise(function (resolve, reject) {
        setTimeout(function () {
          var len = _this4.x * _this4.y;
          var arr = new Array(len).fill(0).map(function (_, i) {
            return i;
          });
          var shuffle = function shuffle(arr) {
            return arr.sort(function () {
              return 0.5 - Math.random();
            });
          };
          var shuffleArray = shuffle(arr);
          // console.log(shuffleArray);
          cells.forEach(function (cell, index) {
            var newPosition = shuffleArray[index];
            cell.instance.style.top = Math.floor(newPosition / _this4.x) * _this4.size + "px";
            cell.instance.style.left = newPosition % _this4.x * _this4.size + "px";
          });
        }, 0);
        setTimeout(function () {
          _this4.regenCellMap();
          _this4.genCellMap();
          _this4.genLoop();
          resolve("ok");
        }, 500);
      });
    }
  }, {
    key: "genLoop",
    value: async function genLoop() {
      await gameMap.genCollapse();
      var status = cells.some(function (cell) {
        return cell.status == "collapse";
      });
      while (cells.some(function (cell) {
        return cell.status == "collapse";
      })) {
        await gameMap.genDownfall();
        await gameMap.genEmerge();
        await gameMap.genCollapse();
      }
      if (removeNum) {
        shownTips(removeNum);
        removeNum = 0;
      }
      gameMap.handleable = true;
      return status;
    }
  }, {
    key: "regenCellMap",
    value: function regenCellMap() {
      var size = gameMap.size;
      var findInstance = function findInstance(x, y) {
        var _cells$find;
        return (_cells$find = cells.find(function (item) {
          var _item$instance = item.instance,
            offsetLeft = _item$instance.offsetLeft,
            offsetTop = _item$instance.offsetTop;
          return item.status != "collapse" && x == offsetLeft / size && y == offsetTop / size;
        })) === null || _cells$find === void 0 ? void 0 : _cells$find.instance;
      };
      this.genMatrix();
      this.matrix = this.matrix.map(function (row, rowIndex) {
        return row.map(function (item, itemIndex) {
          var _findInstance;
          return (_findInstance = findInstance(itemIndex, rowIndex)) === null || _findInstance === void 0 ? void 0 : _findInstance.type;
        });
      });

      // console.log(this.matrix);

      this.init();
    }
  }, {
    key: "genCellMap",
    value: function genCellMap() {
      app.innerHTML = "";
      cells.forEach(function (cell) {
        app.append(cell.instance);
      });
      // console.log(cells);
      return this;
    }
  }]);
  return GameMap;
}();
var Cell = /*#__PURE__*/function () {
  function Cell(options) {
    _classCallCheck(this, Cell);
    var position = options.position,
      status = options.status,
      type = options.type,
      left = options.left,
      top = options.top,
      right = options.right,
      bottom = options.bottom,
      instance = options.instance;
    this.type = type;
    this.position = position;
    this.status = status;
    this.top = top;
    this.bottom = bottom;
    this.left = left;
    this.right = right;
    this.instance = instance;
  }
  _createClass(Cell, [{
    key: "genCell",
    value: function genCell() {
      var cell = document.createElement("div");
      var size = gameMap.size;
      var _this$position = _slicedToArray(this.position, 2),
        x = _this$position[0],
        y = _this$position[1];
      cell.type = this.type;
      cell.style.cssText = "\n\t\t\t\twidth:".concat(size, "px;\n\t\t\t\theight:").concat(size, "px;\n\t\t\t\tleft:").concat(size * x, "px;\n\t\t\t\ttop:").concat(size * y, "px;\n\t\t\t\tbox-sizing:border-box;\n\t\t\t\tborder:5px solid transparent;\n\t\t\t\ttransition:0.5s;\n\t\t\t\tposition:absolute;\n\t\t\t\ttransform:scale(").concat(this.status == "emerge" ? "0" : "1", ");\n\t\t\t\tdisplay:flex;\n\t\t\t\tjustify-content:center;\n\t\t\t\talign-items:center\n\t\t\t\t");
      cell.innerHTML = "<img style=\"width:45px;cursor:pointer;transform: scale(1.1);\" src=\"".concat(emojis[this.type], "\">");
      this.instance = cell;
    }
  }]);
  return Cell;
}();
var gameMap = new GameMap(6, 10, 50);
var cell1 = null;
var cell2 = null;
function checkIfFinish() {
  // 大模型生成
  var countdownElement = document.querySelector(".countdown"); // 大模型生成
  return countdownElement.innerText === "已结束"; // 大模型生成
} // 大模型生成

app.onclick = function () {
  if (checkIfFinish()) {
    return;
  }
  if (gameMap.handleable) {
    var target = event.target.parentNode;
    var _target$style = target.style,
      x = _target$style.left,
      y = _target$style.top;
    var _cell = cells.find(function (item) {
      return item.instance == target;
    });
    if (!gameMap.useSwap) {
      target.className = "active";
      cell1 = _cell;
    } else {
      cell2 = _cell;
      cell1.instance.className = "";
      if (["left", "top", "bottom", "right"].some(function (item) {
        return cell1[item] == cell2;
      })) {
        (async function () {
          await gameMap.genSwap(cell1, cell2);
          var res = await gameMap.genLoop();
          if (!res) {
            await gameMap.genSwap(cell1, cell2);
          }
        })();
      }
    }
    gameMap.useSwap = !gameMap.useSwap;
  }
};
btn.onclick = function () {
  // 隐藏已结束
  end.style.display = 'none';
  // 重置积分
  totalNum = 0;
  setTotalNum(totalNum);
  // 重置计时器
  var countdownEm = document.getElementsByClassName("countdown")[0];
  countdownEm.innerHTML = '1分钟';
  updateCountdown();
  // 刷新页面
  gameMap.genShuffle();
};
var timer;
// 1分钟计时器
function updateCountdown() {
  // 大模型生成
  // 获取需要显示时间的元素
  var timeElement = document.querySelector('.countdown'); // 大模型生成
  // 定义倒计时时间,单位为秒
  var timeLeft = 60; // 大模型生成

  // 如果倒计时时间小于0,则停止倒计时
  if (timeLeft <= 0) {
    // 大模型生成
    clearInterval(timer); // 大模型生成
    return; // 大模型生成
  } // 大模型生成

  // 更新倒计时时间
  timer = setInterval(function () {
    // 大模型生成
    timeLeft--; // 大模型生成
    // 将倒计时时间转换为字符串,并将其显示在元素中
    timeElement.textContent = "".concat(timeLeft, "\u79D2"); // 大模型生成

    if (timeLeft <= 0) {
      // 大模型生成
      clearInterval(timer); // 大模型生成
      timeElement.textContent = '已结束'; // 大模型生成
      end.style.display = 'block';
      return; // 大模型生成
    }
  }, 1000); // 大模型生成
} // 大模型生成

var cover = document.querySelector(".cover"); // 大模型生成
var end = document.querySelector(".end");
cover.addEventListener("click", function () {
  // 大模型生成
  cover.style.display = 'none'; // 大模型生成

  totalNum = 0;
  setTotalNum(totalNum);
  gameMap.genMatrix().genRandom();
  gameMap.init().genCellMap();
  gameMap.genLoop();
  updateCountdown();
}); // 大模型生成